package org.jeecg.modules.demo.signatureCA.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.jeecg.modules.demo.signatureCA.entity.TTGcasign;
import org.jeecg.modules.demo.signatureCA.mapper.SignatureCAMapper;
import org.jeecg.modules.demo.signatureCA.service.ISignatureCAService;
import org.jeecg.modules.demo.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@DS("multi-datasource1")
@Service
public class SignatureCAServiceImpl implements ISignatureCAService {



    @Autowired
    private SignatureCAMapper signatureCAMapper;


    @Override
    public Map<String, Object> getGlHeInfoById(String hetId) {
        Map ret = null;
        try {
//            String sql = "select * from V_ECP_HETGLINFO t where  t.hetid=? ";
//            List list = baseDao.getBySqlForMap(sql, hetId);
//            List list = signatureCAMapper.getGlHeInfoById(hetId);
            ret = signatureCAMapper.getHeInfoById(hetId).get(0);
//            if (!list.isEmpty()) {
//                ret = (Map) list.get(0);
//            }
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ret;
    }


    public Map<String, Object> getHeInfoById(String hetId) {
        Map<String, Object> ret = null;
        try {
//            String sql = "select * from v_ecp_hetinfo t where  t.hetid=? ";
//            List list = baseDao.getBySqlForMap(sql, hetId);
//            List list = signatureCAMapper.getHeInfoById(hetId);
            ret = signatureCAMapper.getHeInfoById(hetId).get(0);
//            if (!list.isEmpty()) {
//                ret = (Map) list.get(0);
//            }
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ret;
    }


    /**
     * 根据合同号获取报单信息(水路)
     *
     * @param hetId
     * @return
     */
    @Override
    public Map<String, Object> getHeSLInfoById(String hetId) {
        Map ret = null;
        try {
//            String sql = "select * from v_ecp_hetslinfo t where  t.hetid=? ";
//            List list = baseDao.getBySqlForMap(sql, hetId);
//            List list = signatureCAMapper.getHeSLInfoById(hetId);
            ret = signatureCAMapper.getHeSLInfoById(hetId).get(0);
//            if (!list.isEmpty()) {
//                ret = (Map) list.get(0);
//            }
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ret;
    }



    public List searchca(String hetid, String signtag, String signtag2) {
        // TODO Auto-generated method stub
        String ret = null;
        String signclob = "";
        String preclob = "";
        Map<String, String> map = new HashMap<String, String>();
        List list = new ArrayList();
        try {
//            List<TTGcasign> tg = this.baseDao
//                    .getByJpql(
//                            "from TTGcasign where objid=? and signtag=? and sigtype=2 ",
//                            hetid, signtag);
            System.out.println("objid--" + hetid);
            System.out.println("signtag--" + signtag);

            List<TTGcasign> tg = signatureCAMapper.getTTGcasign(hetid,signtag);
            if (!tg.isEmpty() && tg.size() > 0) {
                map.put("signclob", tg.get(0).getSignClob());
                map.put("preclob", tg.get(0).getPreclob());
                map.put("signtag", signtag);
                map.put("sigtype", "2");
                list.add(map);
            } else {
                String orgname = this.getQz(hetid, signtag2);
                if (!orgname.equals("")) {
                    String orggz = orgname + "公章";
                    String orghtz = orgname + "合同章";
                    // 获取签章信息
                    String qzimg = findQzcode(orghtz);
                    if (null != qzimg
                            && (qzimg.equals("1") || qzimg.equals("2"))) {
                        qzimg = findQzcode(orggz);
                        map.put("qzimg", qzimg);
                        map.put("signtag", signtag);
                        map.put("sigtype", "1");
                        list.add(map);
                    }
                    else {
                        map.put("qzimg", qzimg);
                        map.put("signtag", signtag);
                        map.put("sigtype", "1");
                        list.add(map);
                    }

                } else {
                    map.put("qzimg", "");
                    map.put("signtag", signtag);
                    map.put("sigtype", "1");
                    list.add(map);
                }

            }

        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }


    public String findQzcode(String qymc) {
        String ret = null;
        // CloseableHttpClient httpclient = null;
        try {
            // String url =
            // "http://192.168.151.20:8089/inc/aipserver/GetSealData.php?SEAL_NAME="
            // + URLEncoder.encode(qymc, "gbk");
            // httpclient = HttpClients.createDefault();
            // HttpGet httpget = new HttpGet(url);
            // CloseableHttpResponse response = httpclient.execute(httpget);
            // HttpEntity entity = response.getEntity();
            // ret = EntityUtils.toString(entity);
            // EntityUtils.consume(entity);

            //String url1 = "http://47.94.240.187:8086/v2/api/seal/getSealBase64ByUserId";
            String url1 = "http://192.168.181.16:53207/v2/api/seal/getSealBase64ByUserId";
            String jsonString = "{callValue:\'" + qymc + "\',callType:3}";

            RestTemplate restTemplate = new RestTemplate();
            ret = restTemplate.postForObject(url1,
                    JSONObject.fromObject(jsonString), String.class);

            JSONObject jsonObject = JSONObject.fromObject(ret);

            if (jsonObject.get("code").toString().equals("200")) {
                JSONArray jsonArray = (JSONArray) jsonObject.get("data");
                if (jsonArray != null && jsonArray.size() > 0)
                    ret = jsonArray.getString(0);
            }
            else {
                ret = "1";
            }

        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally {
            // 关闭连接,释放资源
            // try {
            // httpclient.close();
            // } catch (Exception e) {
            // e.printStackTrace();
            // }
        }
        return ret;
    }


    public String getQz(String hetid, String qzlx) {
        String ret = "";
//        String sql = " select YINZMC as  qzimg from T_QIANZ where DANJID=? and QIANZLX=? ";
        try {
//            List list = baseDao.getBySqlForMap(sql, hetid, qzlx);
            List<Map<String, Object>> list = signatureCAMapper.getQz(hetid,qzlx);

            if (!list.isEmpty() && list.size() > 0) {
                ret = list.get(0).get("qzimg").toString();
            }

        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ret;
    }



    public Map<String, Object> getUserAndTraderByUserid(String userid) {
        Map<String, Object> userAndTrader = null;
        long luserid = Long.parseLong(userid);
        try {
            List<Map<String, Object>> list = signatureCAMapper.getUserAndTraderByUserid(userid);
            if (!list.isEmpty()) {
                userAndTrader = list.get(0);
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return userAndTrader;
    }



    public Map<String, Object> getTraderInfoById(String traderid) {
        Map<String, Object> trader = null;

        try {
            Long strtraderid = Long.parseLong(traderid);
            List<Map<String, Object>> traderlist = signatureCAMapper.getTraderInfoById(strtraderid);
            trader = traderlist.get(0);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return trader;
    }





    public boolean getQzZT(String hetid, String qzlx) {
        // TODO Auto-generated method stub
        boolean ret = false;
//        String sql = " select * from T_QIANZ where DANJID=? and QIANZLX=? ";
        try {
//            List list = this.baseDao.getBySqlForMap(sql, hetid, qzlx);
            List<Map<String, Object>> list = signatureCAMapper.getQzZT(hetid,qzlx);
            if (!list.isEmpty() && list.size() > 0) {
                ret = true;
            }

        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ret;
    }


    public boolean getSign(String hetid, String signtag) {
        // TODO Auto-generated method stub
        boolean ret = false;
//        String sql = " select * from CA_SIGN where objid=? and signtag=?";
        try {
//            List list = this.baseDao.getBySqlForMap(sql, hetid, signtag);
            List<Map<String, Object>> list = signatureCAMapper.getSign(hetid,signtag);
            if (!list.isEmpty() && list.size() > 0) {
                ret = true;
            }

        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ret;
    }


    public boolean searchSignClob(String signclob) {
        // TODO Auto-generated method stub
        boolean ret = false;
        if (signclob != null) {
            ret = true;
        }
        return ret;
    }

    public boolean saveCustomQz(String hetid, String qzlx, String orgname) {
        // TODO Auto-generated method stub
        boolean ret = false;
        String qzid = "";
        String isimage = "1";
        try {
            qzid = genrateId("T_QIANZ");
//            String insertsql = " insert into T_QIANZ(QIANZID,SYSID,DANJLX,DANJID,QIANZLX,ISIMAGE,YINZMC,QIANZSJ)  values (?,?,?,?,?,?,?,?) ";
//            this.baseDao.executeBySQL(insertsql, qzid, qzid, "10", hetid, qzlx, '1', orgname, new Date());
            signatureCAMapper.saveCustomQz(qzid,"10", hetid, qzlx, isimage, orgname, new Date());
            ret = true;
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return ret;
    }







    @Transactional(rollbackFor = Exception.class)
    public String insertSign(HttpServletRequest request, String objtag, String utype, String signClob, String sigtype, TTGcasign ttgcasign) {
        // TODO Auto-generated method stub
        String ret = "";
        // 生成序列化id
        // Long.parseLong(commonService.getSequence("SEQ_CA_SIGN"));
        // DateUtil.getLongFormatNow();
        try {
            String userid = request.getParameter("userid");
            String signclob = signClob;
            String preclob = request.getParameter("htyuanma");
            String hetid = request.getParameter("hetid");

            if (signclob != null && preclob != null) {
                ret = "{'result':'插入成功'}";
                ttgcasign.setSignId(Long.parseLong(this.genrateId("CA_SIGN")));
                ttgcasign.setSignTime(DateUtil.getLongFormatNow());
                ttgcasign.setSignClob(signclob);
                ttgcasign.setPreclob(preclob);
                ttgcasign.setUserId(Long.parseLong(userid));
                ttgcasign.setObjId(hetid);
                ttgcasign.setObjTag(objtag);
                ttgcasign.setSignTag(utype);
                ttgcasign.setSigtype(sigtype);
//                this.baseDao.save(ttgcasign);
                signatureCAMapper.insertSign(ttgcasign);
            } else {
                ret = "{'result':'插入失败'}";
            }
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // ttgcasign.setSysid(Long.parseLong(commonService.getSequence("SEQ_CA_SIGN")));

        return ret;
    }



    public String genrateId(String tableName) {
        String ret = "";
        String sql = "select PAGCTS.GenerateId('" + tableName + "') as genrateid from dual";
        try {
//            List list = baseDao.getBySql(sql);
            List list = signatureCAMapper.genrateId(tableName);
            if (!list.isEmpty()) {
                ret = list.get(0).toString();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

}
